<?php
declare (strict_types = 1);

namespace app\controller;

// 引入校验
use app\validate\Member as MemberValidate;
use think\exception\ValidateException;


// 引入缓存
use think\facade\Cache;

use tinywan\JWT;
use tinywan\exception\JWTRefreshTokenExpiredException;


use think\Request;



// 用户model类
use app\model\Member as MemberModel;

class Login extends Base
{
    /**
     * 登录账户
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function index(Request $request)
    {
        // 接收数据
        $params = request()->rsa_data;
        try {
            // 登录规则检查
            validate(MemberValidate::class)->scene('login')->check($params);
            // 获取指定用户信息
            $user = MemberModel::where('username', $params['username'])->find();
            if(empty($user)){
                // 用户为空
                return $this->createMsg([], '用户名输入错误!', 400);
            }
            // 密码校验
            if(!md5_password_check($params['password'],$user['password'],$user['salt'])){
                return $this->createMsg([], '密码输入错误!', 400);
            }
            if ($user['is_check'] !== 1) {
                return $this->createMsg([], '抱歉您当前尚未有登录权限!', 400);
            }
            // 加密存储在头部的信息
            $tokenInfo = [
                'id' => $user['id'], 
                'username' => $user['username'], 
                'time' => (string)time(), 
                'ip' => get_real_ip()
            ];
            // 将信息给到jwt加密
            // $token = JWTAuth::builder($tokenInfo);
            // $token = \tinywan\JWT::generateToken($tokenInfo);
            $token = Jwt::generateToken($tokenInfo);
            // redis存储已登录信息
            Cache::set("login-user:{$user['id']}:info", $tokenInfo);
            Cache::set("login-user:{$user['id']}:jwt", $token);
            // 将登录的信息返回
            return $this->createMsg(['account'=>$user['account'],'nickname'=>$user['nickname'],'jwt'=>$token], '登录成功!', 200);
            // return $this->createMsg(['token'=>$token], '登录成功!', 200);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->createMsg([], $e->getError(), 400);
        }
    }
    
    /**
     * 退出账户
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function logout(Request $request)
    {
        // // 获取请求头上的jwtToken
        // $token = $request->header('Authorization');
        // // 接收数据
        // $params = request()->rsa_data;
        // // Cache::set("blacklist_token", $params['token'], 60);
        // $blacklist_token = Cache::get('blacklist_token');
        // if(empty($blacklist_token)){
        //     Cache::set("blacklist_token", $params['token'], 60);
        // }
        
        // return $this->createMsg([],'已退出!',200);
        // try {
        //     //可验证token, 并获取token中的payload部分
        //     $payload = JWTAuth::auth($token);
        //     dump($payload);
        // }catch (TokenExpiredException $e){
        //     return $this->createMsg([],'已退出!',407);
        // }catch (TokenInvalidException $e){
        //     return $this->createMsg([],'已退出!',407);
        // }catch (\Exception $e){
        //     return $this->createMsg([],$e->getMessage(),400);
        // }
    }
    
    /**
     * 刷新token
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function refresh(Request $request)
    {
        try {
            // $refreshToken = \tinywan\JWT::refreshToken();
            $refreshToken = Jwt::refreshToken();
            return $this->createMsg($refreshToken,'刷新token!',200);
        } catch (JWTRefreshTokenExpiredException $e){
            return $this->createMsg([],'请重新登录!',407);
        } catch (\Exception $e){
            return $this->createMsg([],$e->getMessage(),400);
        }
    }
}